package com.yoyo.wauth.controller;

import com.yoyo.common.core.enums.ErrorCode;
import com.yoyo.common.core.service.ErrorMessageService;
import com.yoyo.common.core.utils.StringUtils;
import com.yoyo.common.core.web.controller.BaseController;
import com.yoyo.common.core.web.domain.AjaxResult;
import com.yoyo.common.security.utils.SecurityUtils;
import com.yoyo.user.domain.UserInfoVO;
import com.yoyo.user.mapper.UserInfoMapper;
import com.yoyo.wauth.domain.form.ChangePasswordBody;
import com.yoyo.wauth.domain.form.LoginBody;
import com.yoyo.wauth.domain.form.RegisterBody;
import com.yoyo.wauth.mapper.RegisterUserMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Locale;

@Tag(name = "登录认证", description = "登录相关接口")
@RestController
@RequestMapping("/app")
public class LoginController extends BaseController {

    @Autowired
    private RegisterUserMapper registerUserMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;


    @Operation(summary = "用户登录", description = "用户登录接口")
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody body) {
        return AjaxResult.success();
    }

    @Operation(summary = "用户注册")
    @PostMapping("/register")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult register(@RequestBody RegisterBody body) {
        // 参数校验
        if (StringUtils.isEmpty(body.getAccount()) || StringUtils.isEmpty(body.getPassword())) {
            return AjaxResult.error(ErrorCode.CODE_10001,Locale.getDefault());
        }
        // 使用synchronized块确保线程安全
        synchronized (this) {
            // 检查用户是否存在
            if (registerUserMapper.checkUserExistsByUsername(body.getAccount())==1) {
                return AjaxResult.error(ErrorCode.CODE_10002,Locale.getDefault());
            }
            // 生成unique_id
            userInfoMapper.generateUniqueId();
            Integer uniqueId = userInfoMapper.getLastGeneratedUniqueId();

            // 构建用户基础信息
            UserInfoVO userInfo = UserInfoVO.builder()
                    .userName(body.getAccount())
                    .uniqueId(uniqueId)
                    .avatar("https://default-avatar.cdn.com/avatar.png") // 设置默认头像
                    .gender(0) // 默认性别未知
                    .build();
            userInfoMapper.insertUser(userInfo);

            return AjaxResult.success("注册成功");

        }
    }
    @Operation(summary = "密码修改")
    @PostMapping("/changePassword")
    public AjaxResult changePassword(@RequestBody ChangePasswordBody body) {
        if (StringUtils.isEmpty(body.getNewPassword()) || StringUtils.isEmpty(body.getPassword())) {
            return AjaxResult.error();
        }
        return AjaxResult.success();
    }


}
